#coding=utf-8

import re


class Pager:
    _pattern='\s*SELECT\s+(.*)\s+FROM'

    def __init__(self,model,return_keys,sql,values=[]):
        replace_str=re.match(self._pattern,sql).group(1).strip()
        first_one = replace_str.split(',')[0].strip()
        new_str = ' COUNT(%) ' % first_one
        self.count_sql = sql.replace(replace_str,new_str,1)
        self.sql=sql
        self.values=values
        self.model=model
        self.return_keys=return_keys

    def page(self,page,each_page):
        assert page>1
        count_res=self.model.query(self.count_sql,self.values)[0][0]
        start=(page-1)*each_page
        limit_str=' LIMIT %s,%s ' % (start,each_page)
        page_sql = self.sql+limit_str
        max_page=int(count_res/each_page)+1 if count_res%each_page else int(count_res/each_page)
        cur_page = max_page if page>max_page else page
        query_res = self.model.query(page_sql,self.values)
        return {
            'cur_page':cur_page,
            'total_page':max_page,
            'data':[dict(zip(self.return_keys,each)) for each in query_res]
        }

